package com.spark.client.example;

import com.spark.client.SparkClient;
import com.spark.client.config.SparkConfig;
import com.spark.client.exception.SparkClientException;
import com.spark.client.model.SparkResponse;
import com.spark.client.tool.SparkTool;
import com.spark.client.tool.ToolCallHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.HashMap;
import java.util.Map;

/**
 * SparkClient 使用示例
 */
@SpringBootApplication
public class SparkClientExample implements CommandLineRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(SparkClientExample.class);
    
    @Autowired
    private SparkConfig sparkConfig;
    
    @Autowired
    private ToolCallHandler toolCallHandler;

    public static void main(String[] args) {
        SpringApplication.run(SparkClientExample.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("开始 SparkClient 示例演示");
        
        // 基本对话示例
        basicChatExample();
        
        // 链式调用示例
        builderExample();
        
        // 流式调用示例
        streamExample();
        
        // 工具调用示例
        toolCallExample();
        
        logger.info("SparkClient 示例演示完成");
    }

    /**
     * 基本对话示例
     */
    private void basicChatExample() {
        logger.info("=== 基本对话示例 ===");
        
        try {
            SparkClient client = new SparkClient(sparkConfig);
            SparkResponse response = client.chat("你好，请介绍一下你自己");
            
            if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                logger.info("AI 回复: {}", content);
            }
            
        } catch (SparkClientException e) {
            logger.error("基本对话示例失败", e);
        }
    }

    /**
     * 链式调用示例
     */
    private void builderExample() {
        logger.info("=== 链式调用示例 ===");
        
        try {
            SparkClient client = SparkClient.builder(sparkConfig)
                    .model("generalv3.5")
                    .temperature(0.7)
                    .maxTokens(2048)
                    .systemMessage("你是一个专业的编程助手")
                    .userMessage("请解释什么是设计模式")
                    .build();
            
            SparkResponse response = client.chat();
            
            if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                logger.info("AI 回复: {}", content);
            }
            
        } catch (SparkClientException e) {
            logger.error("链式调用示例失败", e);
        }
    }

    /**
     * 流式调用示例
     */
    private void streamExample() {
        logger.info("=== 流式调用示例 ===");
        
        try {
            SparkClient client = SparkClient.builder(sparkConfig)
                    .stream()
                    .userMessage("请写一首关于春天的诗")
                    .build();
            
            StringBuilder fullResponse = new StringBuilder();
            
            client.chatStream(response -> {
                if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                    SparkResponse.Choice choice = response.getChoices().get(0);
                    if (choice.getDelta() != null && choice.getDelta().getContent() != null) {
                        String content = choice.getDelta().getContent();
                        fullResponse.append(content);
                        System.out.print(content); // 实时输出
                    }
                }
            });
            
            System.out.println(); // 换行
            logger.info("完整回复: {}", fullResponse.toString());
            
        } catch (SparkClientException e) {
            logger.error("流式调用示例失败", e);
        }
    }

    /**
     * 工具调用示例
     */
    private void toolCallExample() {
        logger.info("=== 工具调用示例 ===");
        
        try {
            // 注册天气查询函数
            toolCallHandler.registerFunction("get_weather", params -> {
                String location = (String) params.get("location");
                String unit = (String) params.getOrDefault("unit", "celsius");
                
                // 模拟天气查询
                Map<String, Object> weather = new HashMap<>();
                weather.put("location", location);
                weather.put("temperature", 22);
                weather.put("unit", unit);
                weather.put("description", "晴朗");
                
                logger.info("查询天气: {} -> {}", location, weather);
                return weather;
            });
            
            // 创建天气查询工具
            Map<String, Object> properties = new HashMap<>();
            properties.put("location", ToolCallHandler.stringProperty("要查询天气的城市名称"));
            properties.put("unit", ToolCallHandler.enumProperty("温度单位", new String[]{"celsius", "fahrenheit"}));
            
            SparkTool weatherTool = ToolCallHandler.createFunctionTool(
                "get_weather", 
                "查询指定城市的天气信息", 
                properties, 
                new String[]{"location"}
            );
            
            SparkClient client = SparkClient.builder(sparkConfig)
                    .systemMessage("你是一个天气助手，可以查询天气信息")
                    .userMessage("北京今天天气怎么样？")
                    .tool(weatherTool)
                    .build();
            
            SparkResponse response = client.chat();
            
            // 处理工具调用
            Map<String, Object> toolResults = toolCallHandler.handleToolCalls(response);
            if (!toolResults.isEmpty()) {
                logger.info("工具调用结果: {}", toolResults);
            }
            
            if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                logger.info("AI 回复: {}", content);
            }
            
        } catch (SparkClientException e) {
            logger.error("工具调用示例失败", e);
        }
    }
}
